<?php
class Customer extends CS_Controller
{
    public function _init()
    {
        $this->load->helpers('common');
        $this->load->library('pagination');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('carry_log_model', 'carry_log');
        $this->load->model('recharge_log_model', 'recharge_log');
        $this->load->model('rebate_log_model', 'rebate_log');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('user_account_list_model', 'user_account_list');
        $this->load->model('withdraw_model', 'withdraw');
        $this->load->model('deposit_model', 'deposit');
        $this->load->model('transfer_record_model', 'transfer_record');
    }

    /**
     * 个人信息
     */
    public function personal()
    {
        $result = $this->user->findOne(['uid'=>$this->uid]);
        $data['useInfo'] = $result->row();
        $userAccount = $this->user_account->findByUid($this->uid);
        $data['balance'] = $userAccount->row();
        $this->load->view('customer/personal', $data);
    }
    
    /**
     * 验证用户是否注册过。
     */
    public function validateMobilePhone()
    {
        $result = $this->user->validateMobilePhone($this->input->post());
        if ($result->num_rows() > 0) {
            echo 'false';
        } else {
            echo 'true';
        }
        exit;
    }

    /**
     * 提交修改个人信息
     */
    public function editPostPersonal()
    {
        $postData    = $this->input->post();
        $mobilePhone = $this->input->post('mobile_phone');
        $cellphone   = $this->input->post('cellphone');
        $sex_id      = $this->input->post('sex_id');
        $birthday    = $this->input->post('birthday');
        if ($mobilePhone && !valid_mobile($mobilePhone)) {
            $this->error('customer/personal', '', '手机号码有误，请检查~');
        }
        if ($cellphone && !valid_mobile($cellphone)) {
            $this->error('customer/personal', '', '备用手机有误，请检查~');
        }
        if ($sex_id && !in_array($sex_id, [0, 1, 2])) {
            $this->error('customer/personal', '', '性别不合法~');
        }
        if ($birthday) {
            $isDate = strtotime($birthday) ? strtotime($birthday) : false;
            if (!$isDate) {
                $this->error('customer/personal', '', '生日不合法~');
            }
        }
        $update = $this->user->update($postData, ['uid' => $this->uid]);
        if ($update && $this->db->trans_status() === TRUE) {
            $this->success('customer/personal', '', '保存成功！');
        } else {
            $this->error('customer/personal', '', '保存失败！');
        }
    }
    
    /**
     * 检票帐号
     * 修改密码
     */
    public function modifyPw()
    {
        $this->load->view('customer/modifyPw');
    }
    
    /**
     * 检票帐号
     * 修改密码保存
     */
    public function changepwPost()
    {
        if ($this->input->post('password') != $this->input->post('confirm_password')) {
            $this->error('customer/modifyPw', '', '2次密码不一致');
        }
        if (strlen($this->input->post('password')) < 6) {
            $this->error('customer/modifyPw', '', '密码长度必须大于6位');
        }
        $result = $this->user->findByUid($this->uid);
        if ($result->num_rows() <= 0) {
            $this->error('customer/modifyPw', '', '用户不存在');
        }
        $user = $result->row();
        if ($user->pw != md5($this->input->post('oldpwd'))) {
            $this->error('customer/modifyPw', '', '当前密码填写错误');
        }
        $postData = $this->input->post();
        $postData['uid'] = $this->uid;
        $this->db->trans_start();
        $res = $this->user->modifyPassword($postData);
        $this->db->trans_complete();
    
        if ($this->db->trans_status() === TRUE && $res) {
            $this->success('customer/modifyPw', '', '密码修改成功');
        } else {
            $this->error('customer/modifyPw', '', '密码修改失败');
        }
    }
    
    
    /**
     * 账户收支
     */
    public function accountRecord($pg=1)
    {
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $_GET['startData'] = date('Y-m-d', strtotime('-1 month'));
        $_GET['endData'] = date('Y-m-d');
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $config['first_url']   = base_url('customer/accountRecord').$this->pageGetParam($this->input->get());
        $config['suffix']      = $this->pageGetParam($this->input->get());
        $config['base_url']    = base_url('customer/accountRecord');
        $config['total_rows']  = $this->account_log->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['accountRecord'] = $this->account_log->page_list($page_num, $num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $data['levelType'] = $this->levelType();
        $data['accountType'] = $this->accountType();
        $this->load->view('customer/accountRecord', $data);
    }

    /**
     * 账户收支刷新
     */
    public function ajaxAccountRecord($pg = 1)
    {
        $getData = $this->input->get();
        if ($getData['order_id']) {
            $getData['startData'] = '';
            $getData['endData'] = '';
            $getData['type'] = 0;
            $getData['product_type'] = 0;
        } else {
            $type = array('ALL' => 0, 'ONLINE_PROFIT' => ZFPROFIT, 'PAY' => PAY, 'REFUND' => CANCEL);
            if (array_key_exists($getData['type'], $type)) {
                $getData['type'] = $type[$getData['type']];
            } else {
                $this->ajaxJson(false, '收支状态错误');
            }

            $productType = array('ALL', 'SCENIC', 'TOURISM', 'LINE', 'HOTEL', 'DEPOSIT', 'WITHDRAW');
            if (in_array($getData['product_type'], $productType)) {
                $getData['product_type'] = ($getData['product_type'] == 'ALL') ? 0 : strtolower($getData['product_type']);
            } else {
                $this->ajaxJson(false, '收支类型错误');
            }

            if ('deposit' === $getData['product_type']) {
                $getData['type'] = array(VIR_RECH, RECHARGE);
            } elseif ('withdraw' === $getData['product_type']) {
                $getData['type'] = CASH;
            }
        }
        
        $pg = (int)$this->input->get('page');
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $getData['uid'] = $this->uid;
        $config['base_url']    = base_url('customer/accountRecord');
        $config['total_rows']  = $this->account_log->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num; 
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $data['accountRecord'] = $this->account_log->page_list($page_num, $num, $getData);
        $data['levelType'] = $this->levelType();
        $data['accountType'] = $this->accountType();
        echo json_encode(
            array(
                'status' => TRUE,
                'html'   => $this->load->view('customer/ajaxAccountList', $data, TRUE)
            )
        );
        exit;
    }
    
    /**
     * 提现记录
     */
    public function carryRecord($pg=1)
    {
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $_GET['startData'] = date('Y-m-d', strtotime('-1 month'));
        $_GET['endData'] = date('Y-m-d');
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $config['first_url']   = base_url('customer/carryRecord');
        $config['base_url']    = base_url('customer/carryRecord');
        $config['total_rows']  = $this->withdraw->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['withdrawList'] = $this->withdraw->page_list($getData, $page_num, $num);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $this->load->view('customer/carryRecord', $data);
    }
    
    /**
     * ajax提现记录刷新
     */
    public function ajaxCarryRecord()
    {
        $getData = $this->input->get();
        if ($getData['order_id']) {
            $getData['startData'] = '';
            $getData['endData'] = '';
            $getData['withdraw_id'] = $getData['order_id'];
        } else {
            $type = array('ALL', 'AUDIT', 'SUCCESS', 'FAIL');
            if (in_array($getData['condition'], $type)) {
                switch ($getData['condition']) {
                    case 'AUDIT':
                        $getData['state'] = array(0,1); //审核中
                        break;
                    case 'SUCCESS':
                        $getData['state'] = array(2); //2审审核成功
                        $getData['audit_state'] = 1;
                        break;
                    case 'FAIL':
                        $getData['audit_state'] = 2;
                        break;
                    default:
                        break;
                }
            } else {
                $this->ajaxJson(false, '提现状态错误');
            }
        }
        $pg = (int)$this->input->get('page');
        $getData['uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/carryRecord');
        $config['base_url']    = base_url('customer/carryRecord');
        $config['total_rows']  = $this->withdraw->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['withdrawList'] = $this->withdraw->page_list($getData, $page_num, $num);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        echo json_encode(
            array(
                'status' => TRUE,
                'html'   => $this->load->view('customer/ajaxCarryList', $data, TRUE)
            )
        );
        exit;
    }

    /**
     * 提现记录
     */
    public function rechargeRecord($pg=1)
    {
        $_GET['startData'] = date('Y-m-d', strtotime('-1 month'));
        $_GET['endData'] = date('Y-m-d');
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/rechargeRecord');
        $config['base_url']    = base_url('customer/rechargeRecord');
        $config['total_rows']  = $this->deposit->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['depositList'] = $this->deposit->page_list($getData, $page_num, $num);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $this->load->view('customer/rechargeRecord', $data);
    }

    /**
     * ajax刷新充值记录
     */
    public function ajaxRechargeRecord()
    {
        $getData = $this->input->get();
        if ($getData['order_id']) {
            $getData['startData'] = '';
            $getData['endData'] = '';
            $getData['deposit_id'] = $getData['order_id'];
        } else {
            $type = array('ALL', 'SUCCESS', 'FAIL');
            if (in_array($getData['condition'], $type)) {
                switch ($getData['condition']) {
                    case 'SUCCESS':
                        $getData['state'] = 2; //2审审核成功
                        break;
                    case 'FAIL':
                        $getData['state'] = 1;
                        break;
                    default:
                        break;
                }
            } else {
                $this->ajaxJson(false, '提现状态错误');
            }
        }
        $pg = (int)$this->input->get('page');
        $getData['uid'] = $this->uid;

        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/rechargeRecord').$this->pageGetParam($this->input->get());
        $config['suffix']      = $this->pageGetParam($this->input->get());
        $config['base_url']    = base_url('customer/rechargeRecord');
        $config['total_rows']  = $this->deposit->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['depositList'] = $this->deposit->page_list($getData, $page_num, $num);
        echo json_encode(
            array(
                'status' => TRUE,
                'html'   => $this->load->view('customer/ajaxRechargeList', $data, TRUE)
            )
        );
        exit;
    }
    
    /**
     * 返利记录
     */
    public function rebateRecord($pg=1)
    {
        $_GET['startData'] = date('Y-m-d', strtotime('-1 month'));
        $_GET['endData'] = date('Y-m-d');
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/rebateRecord');
        $config['base_url']    = base_url('customer/rebateRecord');
        $config['total_rows']  = $this->rebate_log->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['rebateRecord'] = $this->rebate_log->page_list($page_num, $num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $this->load->view('customer/rebateRecord', $data);
    }

    /**
     * ajax刷新返利记录
     */
    public function ajaxRebateRecord()
    {
        $getData = $this->input->get();
        if ($getData['order_id']) {
            $getData['startData'] = '';
            $getData['endData'] = '';
            $getData['id'] = $getData['order_id'];
        } else {
            $type = array('ALL', 'AUDIT','SUCCESS', 'FAIL');
            if (in_array($getData['condition'], $type)) {
                switch ($getData['condition']) {
                    case 'AUDIT':
                        $getData['flag'] = 1; //申请中
                        break;
                    case 'SUCCESS':
                        $getData['flag'] = 2; //申请成功
                        break;
                    case 'FAIL':
                        $getData['flag'] = 4; //申请失败
                        break;
                    default:
                        break;
                }
            } else {
                $this->ajaxJson(false, '提现状态错误');
            }
        }
        $pg = (int)$this->input->get('page');
        $getData['uid'] = $this->uid;

        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/rebateRecord');
        $config['base_url']    = base_url('customer/rebateRecord');
        $config['total_rows']  = $this->rebate_log->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['rebateRecord'] = $this->rebate_log->page_list($page_num, $num, $getData);
        echo json_encode(
            array(
                'status' => TRUE,
                'html'   => $this->load->view('customer/ajaxRebateList', $data, TRUE)
            )
        );
        exit;
    }

    /**
     * 扫码记录
     */
    public function scanCodeRecord($pg=1)
    {
        $_GET['startData'] = date('Y-m-d', strtotime('-1 month'));
        $_GET['endData'] = date('Y-m-d');
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/scanCodeRecord');
        $config['base_url']    = base_url('customer/scanCodeRecord');
        $config['total_rows']  = $this->transfer_record->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['scanCodeRecord'] = $this->transfer_record->page_list($getData, $page_num, $num);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $data['transferStatus'] = array(0 => '未出账', 1 => '未出账', 2 => '出账成功', 3 => '出账失败', 4 => '未出账', 5 => '出账失败');
        $this->load->view('customer/scanCodeRecord', $data);
    }

    /**
     * ajax刷新扫码记录
     */
    public function ajaxScanCodeRecord()
    {
        $getData = $this->input->get();
        if ($getData['order_id']) {
            $getData['startData'] = '';
            $getData['endData'] = '';
            $getData['withdraw_id'] = $getData['order_id'];
        } else {
            $type = array('ALL', 'WAIT','SUCCESS', 'FAIL');
            if (in_array($getData['condition'], $type)) {
                switch ($getData['condition']) {
                    case 'WAIT':
                        $getData['transfer_status'] = array(0, 1, 4); //未出账
                        break;
                    case 'SUCCESS':
                        $getData['transfer_status'] = array(2); //成功
                        break;
                    case 'FAIL':
                        $getData['transfer_status'] = array(3, 5); //失败
                        break;
                    default:
                        break;
                }
            } else {
                $this->ajaxJson(false, '结算状态异常');
            }
        }
        $pg = (int)$this->input->get('page');
        $getData['uid'] = $this->uid;

        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/scanCodeRecord');
        $config['base_url']    = base_url('customer/scanCodeRecord');
        $config['total_rows']  = $this->transfer_record->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['scanCodeRecord'] = $this->transfer_record->page_list($getData, $page_num, $num);
        $data['transferStatus'] = array(0 => '未出账', 1 => '未出账', 2 => '出账成功', 3 => '出账失败', 4 => '未出账', 5 => '出账失败');
        echo json_encode(
            array(
                'status' => TRUE,
                'html'   => $this->load->view('customer/ajaxScanCodeList', $data, TRUE)
            )
        );
        exit;
    }
    
    /**
     * 下级会员
     */
    public function JuniorMember($pg=1)
    {
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('customer/JuniorMember').$this->pageGetParam($this->input->get());
        $config['suffix']      = $this->pageGetParam($this->input->get());
        $config['base_url']    = base_url('customer/JuniorMember');
        $config['total_rows']  = $this->user->total(array('uid'=>$this->uid));
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['page_list'] = $this->user->page_list($page_num, $num, array('uid'=>$this->uid));
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $this->load->view('customer/JuniorMember',$data);
    }

    /**
     * 帐号安全
     */
    public function accountSecurity()
    {
        $data['userInfo'] = $this->user->findByUid($this->uid)->row();

        $this->load->view('customer/accountSecurity', $data);
    }

    //结算
    public function rebate()
    {
        $result = $this->user_account->findByUid($this->uid);
        $data['userAccount'] = $result->row();
        $this->load->view('customer/rebate', $data);
    }
    
    /**
     * 执行结算操作
     */
    public function rebateDo()
    {
        if ($this->input->post('o_income') <= 0) {
            $this->error('customer/rebate', '', '结算金额必须要大于零');
        }
        $result = $this->user->getUserAccount(array('uid'=>$this->uid));
        if ($result->num_rows() <= 0) {
            $this->error('customer/rebate', '', '获取用户账户信息失败');
        }
        $userAccount  = $result->row();
        
        if (!((int)$userAccount->user_type&UTID_PROVIDER)) {//UTID_PROVIDER 供应商
            $this->error('customer/rebate', '', '不是供应商账号，不能操作。');
        }
        if ($userAccount->amount_month > 0) {
            $this->error('customer/rebate', '', '月结账号数据有误');
        }
        if ($this->input->post('o_income') > abs($userAccount->amount_month)) {
            $this->error('customer/rebate', '', '申请金额超限');
        }
        if ($this->input->post('deduction') > $userAccount->amount_carry) {
            $this->error('customer/rebate', '', '打款金额小于抵扣金额');
        }
        if ($this->input->post('o_income') < $this->input->post('deduction')) {
            $this->error('customer/rebate', '', '抵扣金额大于打款金额');
        }
        
        $postData = $this->input->post();
        $postData['uid']            = $this->uid;
        $postData['r_income']       = $this->input->post('o_income') - $this->input->post('deduction');
        $postData['n_amount_carry'] = $userAccount->amount_carry - $this->input->post('deduction');
        $postData['n_amount_month'] = $userAccount->amount_month + $this->input->post('o_income');
        
        $postData['order_id']       = 0;
        $postData['type']           = DEDUCTION;
        $postData['account_type']   = ACCOUNT_TYPE_CARRY;
        $postData['product_type']   = 'tourism';
        
        $this->db->trans_start();
        if ($this->input->post('o_income') - $this->input->post('deduction') > 0) { //如果可提现金额大于零
            $result = $this->user_account_list->insertUserAccountList($postData);
        }
        $update = $this->user_account->updateUserAccount($this->uid, $postData);
        
        $insertId = $this->account_log->insertAccountLog($postData);
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === TRUE && $update && $insertId) {
            $this->success('customer/rebateRecord', '', '申请成功，请等待审核！');
        } else {
            $this->error('customer/rebate', '', '抵扣金额大于打款金额');
        }
    }
    
    /**
     * 账户充值
     */
    public function incoming()
    {
        $data['payment'] = $this->pay_method->getAllBankId();
        $this->load->view('customer/incoming', $data);
    }
    
    /**
     * 账户提现
     */
    public function outcoming()
    {
        $result = $this->user->getUserDetail(array('uid'=>$this->uid));
        $data['userDetail'] = $result->row();
        $userAccount = $this->user_account->findByUid($this->uid);
        $data['balance'] = $userAccount->row();
        $this->load->view('customer/outcoming', $data);
    }
}